// 定义状态码消息映射
import eventBus from "src/utils/eventBus.js";
import {useRouter} from "vue-router";

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。'
};

let router = useRouter()
export const conf = {
  host: 'https://www.flopsai.cn:5087',
  sysHost: 'https://agent.flopsai.cn'
}

// 请求配置
const defaultOptions = {
  timeout: 1000 * 30, // 默认超时时间
  headers: {'Content-Type': 'application/json;charset=utf-8'},
  baseURL: process.env.VUE_APP_BASE_API || '', // 请求基地址
  // credentials: 'include'
};

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
  }
  return Promise.reject(error);
};

// 请求拦截器
const requestInterceptor = (config) => {
  const newConfig = {...config};
  const host = newConfig.url.includes('sys-api')?conf.sysHost:conf.host
  // 添加基础URL
  newConfig.url = `${host}${config.url}`;
  // 添加token到header
  const token = localStorage.getItem('token');
  if (token) {
    newConfig.headers['Authorization'] = `Bearer ${token}`;
  } else {

  }
  return newConfig;
};

// 响应拦截器
const responseInterceptor = (response) => {
  if (response.ok) {
    return response.text();
  } else {
    throw response;
  }
};

// 创建一个封装后的fetch函数
const fetchWrapper = (url, options = {}) => {
  const config = requestInterceptor({...defaultOptions, ...options, url});
  // 设置超时
  const controller = new AbortController();
  const {signal} = controller;
  const timeoutId = setTimeout(() => controller.abort(), config.timeout);

  return fetch(config.url, {...config, signal})
    .then((response) => {
      clearTimeout(timeoutId);

      if (response.status == 401) {
        return window.location.href = window.location.origin+'/#/login'
      }
      return new Promise((resolve, reject) => {
        responseInterceptor(response).then((response) => {
          resolve(JSON.parse(response));
        })
      })
    })
    .catch((error) => {
      clearTimeout(timeoutId);
      if (error.status == 401) {
        return eventBus.$emit('showLogin')
      }
      if (error.name === 'AbortError') {
      }
      return errorHandler(error);
    });
};

//为get请求拼装url
function doGetUrl(url, params) {
  url += '?';
  for (let x in params) {
    url += `${x}=${params[x]}&`;
  }
  return url.substr(0, url.length - 1);
}

// 创建一个API客户端类
class APIClient {
  get(url, params, options = {}) {
    url = doGetUrl(url, params)
    return fetchWrapper(url, {...options, method: 'GET'});
  }

  post(url, body, options = {}) {
    return fetchWrapper(url, {...options, method: 'POST', body: JSON.stringify(body)});
  }

  put(url, body, options = {}) {
    return fetchWrapper(url, {...options, method: 'PUT', body: JSON.stringify(body)});
  }

  delete(url, options = {}) {
    return fetchWrapper(url, {...options, method: 'DELETE'});
  }

  //上传文件特殊处理
  uploadFile(url, formData) {
    let token = localStorage.getItem('token');
    return fetch(`${conf.host}${url}`, {
      method: 'POST',
      headers:{
        Authorization : `Bearer ${token}`
      },
      body: formData, // 使用FormData作为body
    })
      .then((response) => {
        if (response.status == 401) {
          return router.push('/login')
        }
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.text(); // 或者 response.json() 取决于服务器返回的数据类型
      })
      .then((res) => {
        return new Promise((resolve, reject) => {
          resolve(JSON.parse(res))
        })
      })
      .catch((error) => {
        if (error.name === 'AbortError') {
        }
        return errorHandler(error);
      });
  }

  //评价部分特殊处理
  httpPassageway(url, option, token) {
    option['headers'] = {'Content-Type': 'application/json;charset=utf-8'};
    option.headers['Authorization'] = `Bearer ${token}`;
    return fetch(`${conf.goHost}${url}`, option)
      .then((response) => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.text(); // 或者 response.json() 取决于服务器返回的数据类型
      })
      .then((res) => {
        return new Promise((resolve, reject) => {
          resolve(JSON.parse(res))
        })
      })
      .catch((error) => {
        return errorHandler(error);
      });
  }
}

export default new APIClient();
